package com.spi.controller;

import com.spi.service.ImageService;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Iterator;

@RestController
@RequestMapping("/survey/02")
public class ImageController {

    @Autowired
    private ImageService imageService ;

    // 压缩图片并返回
    @PostMapping("/compress")
    @CrossOrigin("http://localhost:63342")
    public ResponseEntity<byte[]> compressImage(@RequestParam("file") MultipartFile file,
                                                @RequestParam(defaultValue = "0.8") float quality) {
        try {
            byte[] compressedImage = imageService.compressImageForOCR(file, quality);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_JPEG);
            headers.setContentLength(compressedImage.length);

            return new ResponseEntity<>(compressedImage, headers, HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body(e.getMessage().getBytes());
        }
    }

    // 智能压缩 - 自动调整尺寸和质量
    @PostMapping("/smart-compress")
    public ResponseEntity<byte[]> smartCompress(
            @RequestParam("file") MultipartFile file,
            @RequestParam(defaultValue = "1200") int maxWidth,
            @RequestParam(defaultValue = "1600") int maxHeight,
            @RequestParam(defaultValue = "0.8") float quality) {
        try {
            byte[] compressedImage = imageService.smartCompression(file, maxWidth, maxHeight, quality);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_JPEG);
            headers.setContentLength(compressedImage.length);

            return new ResponseEntity<>(compressedImage, headers, HttpStatus.OK);
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage().getBytes());
        }
    }
}
